using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections;
using System.Globalization;
using MBLocale;

/// <summary>
/// Summary description for AdditionalPageInfo
/// </summary>
public class AdditionalPageInfo
{
    DataSet dsobjects = new DataSet();
    private string PageSetIDMaster = "";
	public AdditionalPageInfo()
	{
		//
		// TODO: Add constructor logic here
		//

        
	}

    public AdditionalPageInfo(string strPagesetRowId,DataSet ds)
    {
        try
        {
            string PageSetIDMaster = strPagesetRowId;


            dsobjects = GetTablesRelatedToPageSetID(strPagesetRowId, ds);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error AdditionalPageInfo "+ex.Message);
        }
    }

    // This will fetch all data related to the current pageset and return the dataset.
    public DataSet GetTablesRelatedToPageSetID(string strPagesetRowId,DataSet dsobjects)
    {
       
            StringBuilder mybuilder = new StringBuilder();

            HDDatabase HDD = new HDDatabase();
            string strBindRowID = "";
            string strbindtables = "";
            string strpageids = "";

        try
        {
            // Get the bindids 
            try
            {
                // GetBind id in Displaygrid page
                if (dsobjects.Tables[dsobjects.Tables["Page"].Rows[0]["af_row_id"].ToString()].Select("control_bind_id <> ''").Length > 0)
                {
                    foreach (DataRow dr in dsobjects.Tables[dsobjects.Tables["Page"].Rows[0]["af_row_id"].ToString()].Select("control_bind_id <> ''"))
                    {
                        mybuilder.Append("'" + dr["control_bind_id"].ToString() + "',");
                    }
                    strBindRowID = mybuilder.ToString().Substring(0, mybuilder.Length - 1);
                }
            }
            catch
            {
                // GetBindid in DynamicScreen page
                if (dsobjects.Tables["PageCtrl"].Select("control_bind_id <> ''").Length > 0)
                {
                    foreach (DataRow dr in dsobjects.Tables["PageCtrl"].Select("control_bind_id <> ''"))
                    {
                        mybuilder.Append("'" + dr["control_bind_id"].ToString() + "',");
                    }
                    strBindRowID = mybuilder.ToString().Substring(0, mybuilder.Length - 1);
                }
            }


            #region old steps to fetch the data for binds
            //if (strBindRowID != "")
            //{
            //    // GetBindTablesName
            //    string strsql = "select bind_table from sy_bnd where af_row_id in (" + strBindRowID + ")";
            //    DataTable dt1 = HDD.GetDataTable(strsql);
            //    if (dt1 != null)
            //    {
            //        StringBuilder buildertablename = new StringBuilder();
            //        foreach (DataRow dr in dt1.Rows)
            //        {
            //            buildertablename.Append("'" + dr["bind_table"].ToString() + "',");
            //        }
            //        strbindtables = buildertablename.ToString().Substring(0, buildertablename.Length - 1);
            //    }
            //}

            //if (strbindtables != "")
            //{

            //    // Get Pageid
            //    try
            //    {
            //        string sql = "select page_id,page_icon,is_next_step_enabled,is_rel_info_enabled from sy_pg where page_table_name in (" + strbindtables + ")";
            //        dsobjects.Tables.Add(HDD.GetDataTable(sql, "PageBindPages").Copy());
            //        StringBuilder builderpageid = new StringBuilder();
            //        if (dsobjects.Tables["PageBindPages"] != null)
            //        {
            //            foreach (DataRow dr in dsobjects.Tables["PageBindPages"].Rows)
            //            {
            //                builderpageid.Append("'" + dr["page_id"].ToString() + "',");
            //            }
            //            strpageids = builderpageid.ToString().Substring(0, builderpageid.Length - 1);
            //        }

            //    }
            //    catch (Exception ex)
            //    {
            //        LogWriter.WriteLog("Error getting Bind Pages: "+ ex.Message);
            //    }
            //}


            //if (strpageids != "")
            //{
# endregion

            if(strBindRowID !="")
            {
                // Get PageSet Info
                string strpagesetids = "";
                try
                {

                    // new modified query to fetch the data for bind fields
                    string sqlgetpageset = "select A.pageset_id as pagesetaf_row_id, B.pageset_id as pageset_id,D.page_icon,A.page_id,B.pageset_name as page_name,A.object_id,C.af_row_id as menu_row_id from sy_pgs_mem A,sy_pgs B, sy_mnu C, sy_pg D where A.page_id = D.page_id and  A.pageset_id=B.af_row_id and  B.pageset_id = C.pageset_id and A.page_id in (select page_id from sy_pg where page_table_name in (select distinct(bind_table) from sy_bnd where af_row_id in (" + strBindRowID + "))) and C.is_active = 'True'"; 
                    dsobjects.Tables.Add(HDD.GetDataTable(sqlgetpageset, "PageSetInfo").Copy());

                    #region old query
                    //StringBuilder builderpagesetid = new StringBuilder();
                    // old query to fetch the data(menu, pagesetid) for the bind fields
                    // string sqlgetpageset = "select A.pageset_id as pagesetaf_row_id, B.pageset_id as pageset_id,A.page_id,B.pageset_name as page_name,A.object_id,C.af_row_id as menu_row_id from sy_pgs_mem A,sy_pgs B, sy_mnu C where A.pageset_id=B.af_row_id and  B.pageset_id = C.pageset_id and page_id in (" + strpageids + ")";
                    //foreach (DataRow dr in dsobjects.Tables["PagesetInfo"].Rows)
                    //{
                    //    builderpagesetid.Append("'" + dr["pageset_id"].ToString() + "',");
                    //}
                    //strpagesetids = builderpagesetid.ToString().Substring(0, builderpagesetid.Length - 1);
                    # endregion

                }
                catch(Exception ex)
                {
                    LogWriter.WriteLog("Error getting pagesetinfo for binds: "+ex.Message);
                }
            }
            try
            {
                // Get all config data related to records that can be shown in related info
                string strsql = "select B.* from sy_acr_mem B, sy_acr A where A.af_row_id = B.acr_id and A.af_row_id = 'cc1325625bc5caed' order by acr_id,mem_seq";
                dsobjects.Tables.Add(HDD.GetDataTable(strsql, "sy_acr_mem").Copy());
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("Error getting from acr mem: "+ex.Message);
            }




            // Get Master Detail objects
            // This will get the child pages,menus for those objects where current object is Master
            try
            {
                //string strsq = "select B.object_id, B.page_id, B.page_name,D.af_row_id as menu_row_id, C.pageset_id from sy_obj_mas_detail A, sy_pgs_mem B, sy_pgs C, sy_mnu D where A.master_obj = B.object_id and C.pageset_id = D.pageset_id and C.af_row_id = B.pageset_id and master_obj = '" + dsobjects.Tables["Page"].Rows[0]["object_id"].ToString() + "'";

                string strsq = "select A.pageset_id as pagesetaf_row_id,C.pageset_id as Pageset_id, A.page_id,A.page_name,A.object_id,D.af_row_id as menu_row_id  from sy_pgs_mem A, sy_obj B, sy_pgs C, sy_mnu D where A.object_id = B.object_id and A.pageset_id = C.af_row_id and C.pageset_id=D.pageset_id and B.af_row_id in (select object_id from sy_obj_mas_detail where master_obj = '" + dsobjects.Tables["page"].Rows[0]["object_id"].ToString() + "')";
                dsobjects.Tables.Add(HDD.GetDataTable(strsq, "DetailofMaster").Copy());
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("Error Getting Detail tables for master: "+ ex.Message);
            }



            // This will get the master pages,menus for those objects where current object is child
            try
            {
                string strsql1 = "select A.pageset_id as pagesetaf_row_id,C.pageset_id as Pageset_id, A.page_id,A.page_name,A.object_id,D.af_row_id as menu_row_id  from sy_pgs_mem A, sy_obj B, sy_pgs C, sy_mnu D where A.object_id = B.object_id and A.pageset_id = C.af_row_id and C.pageset_id=D.pageset_id and B.object_id in (select master_obj from sy_obj_mas_detail where object_id = (select af_row_id from sy_obj where object_id = '" + dsobjects.Tables["Page"].Rows[0]["object_id"].ToString() + "'))";
                dsobjects.Tables.Add(HDD.GetDataTable(strsql1, "MasterofDetail").Copy());
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("Error Getting Master tables for Detail: " + ex.Message);
            }





            // This will get the Next step content to be shown in next step related to the current pageid
            try
            {
                string strsql2 = "select * from sy_pg_steps where page_id ='" + dsobjects.Tables["Page"].Rows[0]["af_row_id"].ToString() + "' order by seq";
                dsobjects.Tables.Add(HDD.GetDataTable(strsql2, "PageSteps").Copy());
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("Error Getting Pages: " + ex.Message);
            }

            return dsobjects;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error Getrelatedtables " + ex.Message);
            return dsobjects;
        }
        finally
        {
            HDD = null;
            mybuilder = null;
        }
        
    }

    /// <summary>
    /// This will add a row to the referenced table with Next Step and Related info sections created.
    /// </summary>
    /// <param name="table1" >Reference table on which the sections has to be created</param>
    /// <param name="tablecellname">ID of the new tablecell that will be added to the table</param>
    /// <param name="pagesetid">PagesetID of the current page</param>
    /// <param name="type">Type of section (1 - Next step, 2 - Related Info)</param>
    /// <param name="pagetype">Type of page (1 - DisplayGrid, 2 - Dynamic screen)</param>
    public void addtablerow(ref HtmlTable table1, string tablecellname, string strPagesetRowID, int type, int pagetype,bool inPageHeader)
    {
        HtmlTableRow td1 = new HtmlTableRow();
        HtmlTableCell tc1 = new HtmlTableCell();
        try
        {
            bool statuspagesteps = false;
            bool statusrelatedinfo = false;

            

            tc1.ID = tablecellname;
            if (type == 1)
            {
                //statuspagesteps =loadpagesteps(strPagesetRowID, ref tc1);

                if (loadpagesteps(strPagesetRowID, ref tc1,inPageHeader))
                {
                    td1.Controls.Add(tc1);

                    table1.Controls.Add(td1);

                    td1 = new HtmlTableRow();
                    tc1 = new HtmlTableCell();
                    td1.Height = "10pt";
                    //td1.BgColor = "red";
                    td1.Controls.Add(tc1);



                    table1.Controls.Add(td1);
                }
            }
            else if (type == 2)
            {
                //statusrelatedinfo = loadrelatedinfo(ref tc1, pagetype);

                if (loadrelatedinfo(ref tc1, pagetype,inPageHeader))
                {
                    td1.Controls.Add(tc1);

                    table1.Controls.Add(td1);

                    td1 = new HtmlTableRow();
                    tc1 = new HtmlTableCell();
                    td1.Height = "10pt";
                    //td1.BgColor = "red";
                    td1.Controls.Add(tc1);



                    table1.Controls.Add(td1);
                }
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error addtablerow :" + ex.Message);
        }
        finally
        {
            td1 = null;
            tc1 = null;
        }
    }

    private bool checkforrightswithobjectid(string objectid)
    {

        HDDatabase Hdd = new HDDatabase();
        bool bRead = false;

        try
        {
            if (HttpContext.Current.Session["roleid"] != null)
            {
                string value = Hdd.GetColumnValue("select [read] from sy_obj_acc where role_id = '" + HttpContext.Current.Session["roleid"].ToString() + "' and object_id = '" + objectid + "'");
                if (value != "")
                {
                    if (value.ToLower() == "true")
                    {
                        bRead = true;
                    }
                }

            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error checkrights :" + ex.Message);
        }
        finally
        {
            Hdd = null;
        }

        return bRead;
    }

    private void loadAdditionalRow(ref HtmlTable mytable)
    {
        HtmlTableRow htr1 = new HtmlTableRow();
        HtmlTableCell htc1 = new HtmlTableCell();
        htc1.NoWrap = true;
        try
        {
            // Added for extra row
            
            htr1.Style.Value = "HEIGHT: 5pt";
            //htr1.BgColor = "Red";
            htc1.ColSpan = 2;
            htc1.Width = "100%";
            htr1.Controls.Add(htc1);

            htc1 = new HtmlTableCell();
            htc1.NoWrap = true;
            htr1.Controls.Add(htc1);
            htr1.Attributes.Add("class", "Grid_Row1");
            mytable.Controls.Add(htr1);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error loadAdditionalRow :" + ex.Message);
        }
        finally
        {
            htr1 = null;
            htc1 = null;
        }
    }


    /// <summary>
    /// Creates the Related Info in the referenced TableCell;
    /// </summary>
    /// <param name="tdrelatedinfo">ref a TableCell on which Section will be created;</param>
    /// <param name="type">Type of page (1 - Display Grid, 2 - DynamicScreen)</param>
    /// <returns></returns>
    public bool loadrelatedinfo(ref HtmlTableCell tdrelatedinfo, int type,bool inPageHeader)
    {
        bool canshowsection = false;
        try
        {
            if (dsobjects.Tables["page"].Rows[0]["is_rel_info_enabled"].ToString().ToLower() == "true") // Check whether related info can be displayed or not
            {

                if (dsobjects.Tables["sy_acr_mem"] != null)
                {

                    HtmlTable ht1 = new HtmlTable();
                    HtmlTableRow htr1 = new HtmlTableRow();
                    HtmlTableCell htc1 = new HtmlTableCell();
                    htc1.NoWrap = true;
                    //htc1.Width = "0px"; // srivatsan
                    htr1.Controls.Add(htc1);
                    htc1 = new HtmlTableCell();
                    htc1.NoWrap = true;
                    Label lblrelatedheader = new Label();
                    if (inPageHeader)
                    {
                        lblrelatedheader.Text = "<img style=\"vertical-align:bottom\" src =Images/rel_info.GIF></img><span style=\"vertical-align:bottom\">&nbsp;Related Information</span>";
                        lblrelatedheader.CssClass = "Controlfont";
                    }
                    else
                    {
                        lblrelatedheader.Text = "<img style=\"vertical-align:bottom\" src =Images/rel_info_24.GIF></img><span style=\"vertical-align:bottom\">&nbsp;Related Information</span>";
                    }
                    //style=\"vertical-align:bottom;\"
                    htc1.VAlign ="bottom";
                    htc1.Controls.Add(lblrelatedheader);
                    htc1.Attributes.Add("class", "pgForm_title");//included by sanal on aug 20, 2009 for FF support
                    htr1.Controls.Add(htc1);

                    htc1 = new HtmlTableCell();
                    htc1.NoWrap = true;
                    //htc1.Width = "0px"; // srivatsan
                    htr1.Controls.Add(htc1);

                    htr1.Attributes.Add("class", "pgForm_title");
                    htr1.Height = "25px";//included by sanal on aug 20, 2009 for FF support
                    //loadPageStepsButtons(ref htr1);
                    htr1.VAlign = "Bottom";
                    ht1.Controls.Add(htr1);

                    ht1.Width = "100%";
                    //htr1.Attributes.Add("class", "Grid_Row1");

                    loadAdditionalRow(ref ht1);


                    string pageafrowid = dsobjects.Tables["Page"].Rows[0]["af_row_id"].ToString();
                    string pageid = dsobjects.Tables["page"].Rows[0]["page_id"].ToString();
                    string object_name = dsobjects.Tables["page"].Rows[0]["object_id"].ToString();
                    //string object_id = dsobjects.Tables["sy_obj"].Select("object_id = '" + object_name + "'")[0]["af_row_id"].ToString();

                    PageIcons icons = new PageIcons();
                    foreach (DataRow dr in dsobjects.Tables["sy_acr_mem"].Rows) // get all record types that can be displayed in related info from sy_acr_mem
                    {
                        if (dr["mem_value3"].ToString().Trim().ToLower() == "true") // if the record can be shown
                        {
                            if (dr["mem_id"].ToString().ToLower() == "bindpages")  // record to be shown in Bind for the Pages
                            {
                                if (dsobjects.Tables["PagesetInfo"] != null)
                                {
                                    if(type != 1)
                                    {
                                        if (dsobjects.Tables["PagesetInfo"].Rows.Count > 0)
                                        {
                                            foreach (DataRow dr1 in dsobjects.Tables["PagesetInfo"].Rows) // Get the DataTable which has the menuid and pagesetid
                                            {
                                                if (checkforrightswithobjectid(dr1["object_id"].ToString()))
                                                {
                                                    Literal myliteral = new Literal();
                                                    string page_id = dr1["page_id"].ToString();
                                                    string pageicon = "Default.PNG";
                                                    if (dsobjects.Tables["PagesetInfo"] != null)
                                                    {
                                                        try
                                                        {
                                                            pageicon = dsobjects.Tables["PagesetInfo"].Select("page_id='" + page_id + "'")[0]["page_icon"].ToString();
                                                            if (pageicon == "")
                                                            {
                                                                pageicon = "Default.PNG";
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            pageicon = "Default.PNG";
                                                        }
                                                    }
                                                    myliteral.Text = "&nbsp;&nbsp;&nbsp;<img src=Images/MBIcons/small/" + pageicon + "></img>&nbsp;<a href=displaygrid.aspx?mn=" + dr1["menu_row_id"].ToString() + "&pgs_id=" + dr1["pagesetaf_row_id"].ToString() + ">" + dr1["page_name"].ToString() + "</a>";
                                                    htc1 = new HtmlTableCell();
                                                    htc1.NoWrap = true;
                                                    htc1.Controls.Add(myliteral);
                                                    htc1.ColSpan = 3;
                                                    htr1 = new HtmlTableRow();
                                                    htr1.Controls.Add(htc1);
                                                    htr1.Attributes.Add("class", "Grid_Row1");
                                                    ht1.Controls.Add(htr1);
                                                    canshowsection = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (dr["mem_id"].ToString().ToLower() == "masterdetailpages") // record to be displayed is master detail page
                            {
                                if(dsobjects.Tables["DetailofMaster"] != null)
                                {
                                    if (dsobjects.Tables["DetailofMaster"].Rows.Count > 0)
                                    {
                                        foreach (DataRow dr2 in dsobjects.Tables["DetailofMaster"].Rows)
                                        {
                                            if (checkforrightswithobjectid(dr2["object_id"].ToString()))
                                            {
                                                Literal myliteral = new Literal();
                                                string page_id = dr2["page_id"].ToString();
                                                myliteral.Text = "&nbsp;&nbsp;&nbsp;<img src=" + icons.geticons(page_id, 1).ToString() + "></img>&nbsp;<a href=displaygrid.aspx?mn=" + dr2["menu_row_id"].ToString() + "&pgs_id=" + dr2["pagesetaf_row_id"].ToString() + ">" + dr2["page_name"].ToString() + "</a>";
                                                htc1 = new HtmlTableCell();
                                                htc1.NoWrap = true;
                                                htc1.Controls.Add(myliteral);
                                                htc1.ColSpan = 3;
                                                htr1 = new HtmlTableRow();
                                                htr1.Controls.Add(htc1);
                                                htr1.Attributes.Add("class", "Grid_Row1");
                                                ht1.Controls.Add(htr1);
                                                canshowsection = true;
                                            }
                                        }
                                    }
                                }
                                if (dsobjects.Tables["MasterofDetail"] != null)
                                {
                                    if (dsobjects.Tables["MasterofDetail"].Rows.Count > 0)
                                    {
                                        foreach (DataRow dr3 in dsobjects.Tables["MasterofDetail"].Rows)
                                        {
                                            if (checkforrightswithobjectid(dr3["object_id"].ToString()))
                                            {
                                                Literal myliteral = new Literal();
                                                string page_id = dr3["page_id"].ToString();
                                                myliteral.Text = "&nbsp;&nbsp;&nbsp;<img src=" + icons.geticons(page_id, 1).ToString() + "></img>&nbsp;<a href=displaygrid.aspx?mn=" + dr3["menu_row_id"].ToString() + "&pgs_id=" + dr3["pagesetaf_row_id"].ToString() + ">" + dr3["page_name"].ToString() + "</a>";
                                                htc1 = new HtmlTableCell();
                                                htc1.NoWrap = true;
                                                htc1.Controls.Add(myliteral);
                                                htc1.ColSpan = 3;
                                                htr1 = new HtmlTableRow();
                                                htr1.Controls.Add(htc1);
                                                htr1.Attributes.Add("class", "Grid_Row1");
                                                ht1.Controls.Add(htr1);
                                                canshowsection = true;
                                            }
                                        }

                                    }
                                }




                            }
                            else // other static related info
                            {
                                HDDatabase Hdd = new HDDatabase();
                                try
                                {

                                    if (checkforrightswithobjectid(dr["mem_value2"].ToString()))
                                    {
                                        try
                                        {
                                            string pageicon = Hdd.GetColumnValue("sy_pg", "page_icon", "object_id ='" + dr["mem_value2"].ToString() + "'");
                                            if (pageicon == "")
                                            {
                                                pageicon = "Default.PNG";
                                            }
                                            string displayname = dr["mem_id"].ToString();
                                            Literal literal1 = new Literal();
                                            literal1.Text = "&nbsp;&nbsp;&nbsp;<img src =Images/MBIcons/small/" + pageicon + "></img>&nbsp;<a href =" + dr["mem_value1"].ToString() + ">" + displayname + "</a>";
                                            //MenuItem mnitem1 = new MenuItem(displayname, dr["mem_id"].ToString(), "Images/MBIcons/small/" + pageicon + "", dr["mem_value1"].ToString());
                                            //mnitem1.ToolTip = "Click here for" + displayname + " Page";


                                            htc1 = new HtmlTableCell();
                                            htc1.NoWrap = true;
                                            htc1.Controls.Add(literal1);
                                            htc1.ColSpan = 3;
                                            htr1 = new HtmlTableRow();
                                            htr1.Controls.Add(htc1);
                                            htr1.Attributes.Add("class", "Grid_Row1");
                                            ht1.Controls.Add(htr1);
                                            canshowsection = true;

                                        }
                                        catch (Exception ex)
                                        {
                                            LogWriter.WriteLog("Error DisplayGrid.aspx RelatedInfo Reports :" + ex.Message);
                                        }
                                    }


                                }
                                catch (Exception ex)
                                {
                                    LogWriter.WriteLog("Error loadrelatedinfo static:" + ex.Message);
                                }
                                finally
                                {
                                    Hdd = null;
                                }

                            }
                        }
                    }


                    ht1.CellSpacing = 0;
                    ht1.CellPadding = 0;
                    loadAdditionalRow(ref ht1);

                    if (canshowsection == true)
                    {
                        tdrelatedinfo.Controls.Add(ht1);
                    }

                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error loadrelatedinfo :" + ex.Message);
        }
        return canshowsection;
    }


    /// <summary>
    /// Creates the page steps in the referenced TableCell;
    /// </summary>
    /// <param name="strPagesetRowID">Page set ID of the current page;</param>
    /// <param name="tdpagesteps">ref a TableCell on which Section will be created;</param>
    /// <returns></returns>
    public bool loadpagesteps(string strPagesetRowID, ref HtmlTableCell tdpagesteps,bool inPageHeader)
    {
        bool canshowsection = false;
        HDDatabase Hdd = new HDDatabase();
        PageIcons icons = new PageIcons();
        //DataSet dsePageInfo = new DataSet();
        PageInfoLoad PIL = new PageInfoLoad();
        try
        {
            if (dsobjects.Tables["Page"].Rows[0]["is_next_step_enabled"].ToString().ToLower() == "true")
            {


                if (dsobjects.Tables["pagesteps"].Rows.Count > 0)
                {

                    HtmlTable mytable = new HtmlTable();
                    Label mylabel = new Label();
                    HtmlTableRow mytablerow = new HtmlTableRow();
                    mytablerow.Attributes.Add("class", "pgForm_title");
                    HtmlTableCell mytablecell = new HtmlTableCell();
                    mytablecell.NoWrap = true;
                    //mylabel.Text = "&nbsp;<img src=" + icons.geticons(dsobjects.Tables["Page"].Rows[0]["page_id"].ToString(), 2).ToString() + "></img>&nbsp;&nbsp;Next Step&nbsp;";
                    if (inPageHeader)
                    {
                        mylabel.Text = "&nbsp;<img style=\"vertical-align:bottom\" src=\"Images/next_step.GIF\"></img><span style=\"vertical-align:bottom\">&nbsp;Next Step&nbsp;</span>";
                        mylabel.CssClass = "controlFont";
                    }
                    else
                    {
                        mylabel.Text = "&nbsp;<img style=\"vertical-align:bottom\" src=\"Images/next_step_24.GIF\"></img><span style=\"vertical-align:bottom\">&nbsp;Next Step&nbsp;</span>";
                    }
                    //mylabel.Text = "&nbsp;<img src=Images/forward.GIF></img>&nbsp;Next Step&nbsp;";
                    mytablecell.Controls.Add(mylabel);
                    mytablecell.NoWrap = true;
                    mytablerow.Controls.Add(mytablecell);
                    if (!inPageHeader)
                    {
                        loadPageStepsButtons(ref mytablerow);
                    }

                    // added new 
                    mytablecell = new HtmlTableCell();
                    mytablecell.Width = "2pt";
                    mytablecell.Controls.Add(new LiteralControl("&nbsp;"));
                    mytablerow.Controls.Add(mytablecell);
                    //


                    mytable.Controls.Add(mytablerow);

                    loadAdditionalRow(ref mytable);



                    foreach (DataRow dr in dsobjects.Tables["pagesteps"].Rows)
                    {

                        if (dr["active"].ToString().ToLower() == "true")
                        {

                            
                            if (dr["type"].ToString().ToLower() == "text")
                            {

                                mytablerow = new HtmlTableRow();
                                mytablerow.Attributes.Add("class", "Grid_Row1");



                                


                                mytablecell = new HtmlTableCell();
                                mytablecell.NoWrap = true;
                                Label mylabel1 = new Label();
                                mylabel1.Text = "&nbsp;&nbsp;" + dr["caption"].ToString() + "";
                                mytablecell.Controls.Add(mylabel1);
                                //mytablecell.ColSpan = 2;
                                //mytablecell.Align = "center";
                                mytablerow.Controls.Add(mytablecell);


                                // added new 
                                mytablecell = new HtmlTableCell();
                                mytablecell.NoWrap = true;
                                mytablecell.Width = "2pt";
                                mytablerow.Controls.Add(mytablecell);
                                //

                                mytablecell = new HtmlTableCell();
                                mytablecell.NoWrap = true;
                                //mytablecell.Width = "2pt";
                                mytablerow.Controls.Add(mytablecell);


                                canshowsection = true;
                            }
                            else if (dr["type"].ToString().ToLower() == "page")
                            {
                                PageIcons icons1 = new PageIcons();
                                try
                                {
                                    
                                    string pageid = dr["name"].ToString();
                                    string sql = "select A.pageset_id as pagesetaf_row_id,B.pageset_id as pageset_id,A.page_id,A.page_name,A.object_id,C.af_row_id as menu_row_id from sy_pgs_mem A, sy_pgs B, sy_mnu C where B.pageset_id=C.pageset_id and B.af_row_id=A.pageset_id and page_id = (select page_id from sy_pg where af_row_id = '"+pageid+"')";
                                
                                    DataTable dt =Hdd.GetDataTable(sql);
                                
                                    if(dt!=null)
                                    {
                                    if (checkforrightswithobjectid(dt.Rows[0]["object_id"].ToString()))
                                    {

                                        mytablerow = new HtmlTableRow();
                                        mytablerow.Attributes.Add("class", "Grid_Row1");



                                        


                                        mytablecell = new HtmlTableCell();
                                        mytablecell.NoWrap = true;

                                        Literal myliteral = new Literal();
                                        myliteral.Text = "&nbsp;&nbsp;<img src =" + icons1.geticons(dt.Rows[0]["page_id"].ToString(), 1) + "></img>&nbsp;<a href = displaygrid.aspx?mn=" + dt.Rows[0]["menu_row_id"].ToString() + "&pgs_id=" + dt.Rows[0]["pagesetaf_row_id"].ToString() + ">" + dt.Rows[0]["page_name"].ToString() + "</a>";
                                        mytablecell.Controls.Add(myliteral);
                                        //mytablecell.ColSpan = 2;
                                        //mytablecell.Align = "center";
                                        mytablerow.Controls.Add(mytablecell);


                                        // added new 
                                        mytablecell = new HtmlTableCell();
                                        mytablecell.NoWrap = true;
                                        mytablecell.Width = "2pt";
                                        mytablerow.Controls.Add(mytablecell);
                                        //
                                        mytablecell = new HtmlTableCell();
                                        mytablecell.NoWrap = true;
                                        //mytablecell.Width = "2pt";
                                        mytablerow.Controls.Add(mytablecell);

                                        canshowsection = true;
                                    }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogWriter.WriteLog("Error displaygrid loadpagenextstep " + ex.Message);
                                }
                                finally
                                {
                                    icons = null;
                                }
                            }


                            mytable.Controls.Add(mytablerow);
                            mytable.CellPadding = 0;
                            mytable.CellSpacing = 0;
                            mytable.Width = "100%";
                            
                            //tdpagesteps.Width = "100%";
                        }
                    }

                    //frmObj.FindControl("ctl00$ContentPlaceHolder3$tdpagesteps").Controls.Add(
                    //this.Master.FindControl("ctl00$ContentPlaceHolder3$tdpagesteps");

                    loadAdditionalRow(ref mytable);

                    if (canshowsection == true)
                    {
                        tdpagesteps.Controls.Add(mytable);
                    }



                }
            }
            
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error loadpagesteps:" + ex.Message);
        }
        finally
        {
            icons = null;
            Hdd = null;
            //dsePageInfo = null;
        }

        return canshowsection;
    }

    private void loadPageStepsButtons(ref HtmlTableRow mytablerow)
    {

        try
        {         
            HtmlTableCell tc1 = new HtmlTableCell();
            tc1.NoWrap = true;

            //LinkButton btnback = new LinkButton();
            //btnback.Attributes.Add("onClick", "javascript:history.back();return false;");

            //btnback.CssClass = "linkBacksmalllogo";
            //btnback.ToolTip = "Previous";
            //tc1.Controls.Add(btnback);

            //Literal litspace = new Literal();
            //litspace.Text = "&nbsp;&nbsp;";
            //tc1.Controls.Add(litspace);



            Label btnback = new Label();
            btnback.Attributes.Add("onClick", "javascript:history.back();return false;");
            btnback.Width = Unit.Pixel(24);
            btnback.Height = Unit.Pixel(24);
            btnback.Visible = true;

            btnback.CssClass = "linkBacksmalllogo SearchPopup";
            btnback.ToolTip = "Previous";
            tc1.Controls.Add(btnback);



            Literal litspace = new Literal();
            litspace.Text = "&nbsp;&nbsp;";
            //litspace.Text = "next step and related info";
            tc1.Controls.Add(litspace);


            LinkButton myhomelink = new LinkButton();
            string hometext = homelink();
            myhomelink.Width = Unit.Pixel(24);
            myhomelink.Height = Unit.Pixel(24);
            myhomelink.Attributes.Add("onclick", "javascript:window.location.href='" + hometext + "';return false;");
            //myhomelink.Click += new EventHandler(myhomelink_Click);
            myhomelink.CssClass = "linkhomesmalllogo";
            myhomelink.ToolTip = "Home";
            myhomelink.Visible = true;
            tc1.Controls.Add(myhomelink);


            //tc1.Controls.Add(litspace);

            tc1.Align = "Right";
            //tc1.BgColor = "red";
            mytablerow.Controls.Add(tc1);

            //tc1 = new HtmlTableCell("&nbsp;");
            //mytablerow.Controls.Add(tc1);
           // litspace = null;
           // btnback = null;
           // myhomelink = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error loadPageStepsButtons:" + ex.Message);
        }
    }

    //void myhomelink_Click(object sender, EventArgs e)
    //{
    //    Navigator ng = new Navigator();
    //    string retrn = ng.getUserHomePage();
    //    ng = null;
    //    //Response.Redirect(retrn);
    //}
    private string homelink()
    {
        string retrn = "";
        try
        {
            
            Navigator ng = new Navigator();
            retrn = ng.getUserHomePage();
            ng = null;
            

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error homlink :"+ ex.Message);
        }
        return retrn;
    }

    // This will create Additional Related records as seperate section and adds it to the referenced HtmlTableCell
    public void GenerateRelatedRecordsSections(DataSet dsPageInfo, string strPagesetRowID, ref HtmlTableCell htctarget)
    {
        int tablecount = 0;
        if (dsPageInfo != null)
        {
            if (dsPageInfo.Tables.Count > 0)
            {
                if (dsPageInfo.Tables["PageRelatedRecords"] != null)
                {
                    if (dsPageInfo.Tables["PageRelatedRecords"].Rows.Count > 0)
                    {
                        HtmlTable htmain = new HtmlTable();
                        htmain.Width = "100%";
                        htmain.CellPadding = 0;
                        htmain.CellSpacing = 0;
                        htmain.Border = 0;
                        HtmlTableRow htrmain = new HtmlTableRow();
                        HtmlTableCell htcmain = new HtmlTableCell();

                        htcmain.Height = "5px";
                        //htcmain.Controls.Add(new LiteralControl("&nbsp;"));
                        htrmain.Controls.Add(htcmain);
                        htmain.Controls.Add(htrmain);

                        foreach (DataRow dr in dsPageInfo.Tables["PageRelatedRecords"].Rows)
                        {
                            bool sectionstatus = false;
                            htrmain = new HtmlTableRow();
                            htcmain = new HtmlTableCell();
                            htcmain.NoWrap = true;

                            HtmlTable htchild =new HtmlTable();
                            string sqlquery = "";
                            if (dsPageInfo.Tables["PageRelatedRecordQueries"] != null)
                            {
                                if(dsPageInfo.Tables["PageRelatedRecordQueries"].Rows.Count>0)
                                {
                                    if (dr["value"].ToString().Trim() != "")
                                    {
                                        DataRow[] drrquery = dsPageInfo.Tables["PageRelatedRecordQueries"].Select("af_row_id='"+dr["value"].ToString()+"'");
                                        if (drrquery.Length > 0)
                                        {
                                            sqlquery = drrquery[0]["report_base_sql"].ToString();
                                        }

                                    }
                                }

                            }
                            htchild = CreateRelatedRecords(dr["page_id"].ToString(), dr["type"].ToString(), dr["title"].ToString(), dr["value"].ToString(),sqlquery);
                            if (htchild.Controls.Count > 0)
                            {
                                tablecount += 1;
                                sectionstatus = true;

                                htcmain.Controls.Add(htchild);
                                htrmain.Controls.Add(htcmain);

                                htmain.Controls.Add(htrmain);


                                // will create a new row  the section
                                htrmain = new HtmlTableRow();
                                htcmain = new HtmlTableCell();
                                htcmain.NoWrap = true;

                                //htcmain.Controls.Add(new LiteralControl("&nbsp;"));
                                if (sectionstatus = true)
                                {
                                    htcmain.Height = "8px";
                                }
                                htrmain.Controls.Add(htcmain);
                                htmain.Controls.Add(htrmain);
                            }
                        }
                        if (tablecount > 0)
                        {
                            htctarget.Controls.Add(htmain);
                        }


                        //if (htmain.Controls.Count > 5)
                        //{
                        //    htctarget.Controls.Add(htmain);
                        //}
                    }
                }
            }
        }
    }

    private HtmlTable CreateRelatedRecords(string pageid,string type,string title,string value,string query)
    {
        HtmlTable htsection = new HtmlTable();
        htsection.Width = "100%";
        htsection.CellPadding = 0;
        htsection.CellSpacing = 0;
        htsection.Border = 0;
        HDDatabase HDD = new HDDatabase();
        if (type.Trim() != "")
        {
            switch(type.Trim().ToLower())
            {
                case "query":
                    {
                        if (value.Trim() != "")
                        {
                            if (query.Trim() != "")
                            {
                                query = ReplaceVariablesinQueries(query);
                                DataTable dt = HDD.GetDataTable(query);
                                SecurityFilter sec = new SecurityFilter();
                                dt = sec.ApplySecurityforDataTable(dt);
                                RemoveOwnerIDField(ref dt);
                                if (dt != null)
                                {
                                    htsection = CreateHtmlTableFromDataTable(dt,title);
                                }
                            }
                        }
                        break;
                    }
                
            }
        }
        return htsection;
    }

    private void RemoveOwnerIDField(ref DataTable dt)
    {
        if (dt != null)
        {
            if (dt.Columns.Contains("owner_id"))
            {
                dt.Columns.Remove("owner_id");
            }
        }
    }

    private string ReplaceVariablesinQueries(string sql)
    {
        if (HttpContext.Current.Session["sysvar"] != null)
        {
            Hashtable hshvar = (Hashtable)HttpContext.Current.Session["sysvar"];

            if (hshvar != null)
            {
                if (sql.Trim().Contains("$") || sql.Trim().Contains("@"))
                {
                    Hashtable hashtemp = new Hashtable();
                    string tempsql = sql;
                    foreach (string a in hshvar.Keys)
                    {
                        if (a.Contains("."))
                        {
                            string[] arr = a.Split('.');
                            if (arr.Length > 0)
                            {
                                int len = arr.Length;
                                hashtemp.Add("$" + arr[len - 1].Trim() + "$", hshvar[a].ToString());
                            }
                        }
                        else
                        {
                            hashtemp.Add(a, hshvar[a].ToString());
                        }
                    }

                    security hdds = new security();
                    hdds.loadAppVariables(ref hashtemp);


                    foreach (string s in hashtemp.Keys)
                    {
                        if (tempsql.Contains(s))
                        {
                            tempsql = tempsql.Replace(s, hashtemp[s].ToString());
                        }
                    }

                    if (tempsql.Trim() != "")
                    {
                        sql = tempsql;
                    }
                }

            }
        }
        return sql;
    }
    private HtmlTable CreateHtmlTableFromDataTable(DataTable dt,string title)
    {
        HtmlTable ht = new HtmlTable();
        ht.Width = "100%";
        ht.CellSpacing = 0;
        ht.CellPadding = 0;
        ht.Border = 0;
        if (dt != null)
        {

            DynamicDisplayI DDI = new DynamicDisplayI();
            string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            DDI = null;

            #region Old code Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
            //Localization loc = new Localization();
            //CultureInfo cul = loc.getUserCulture();
            //loc = null;
            #endregion
            CultureInfo cul = MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString());
            
            //if (dt.Rows.Count > 0)
            //{
                HtmlTableRow htr = new HtmlTableRow();
                HtmlTableCell htc = new HtmlTableCell();

                //if (title != "")
                //{
                    htr.Attributes.Add("class", "grid_header_light");
                    Label lbl = new Label();
                    lbl.Text = "&nbsp;"+title+"&nbsp;";
                    htc.ColSpan = dt.Columns.Count+1;
                    htc.Controls.Add(lbl);
                    htr.Controls.Add(htc);
                    ht.Controls.Add(htr);
                //}

                //Add the header part of the table
                htr = new HtmlTableRow();
                htr.Attributes.Add("Class", "Grid_Header");

                htc = new HtmlTableCell();
                htc.Width = "2px";
                htr.Controls.Add(htc);

                foreach (DataColumn dc in dt.Columns)
                {
                    htc = new HtmlTableCell();
                    SetRelatedRecordsAlignments(ref htc, dc.DataType.ToString());
                    Label lblobj = new Label();
                    lblobj.Text = "&nbsp;" + dc.ColumnName + "&nbsp;";
                    htc.Controls.Add(lblobj);
                    htr.Controls.Add(htc);
                }
                
                ht.Controls.Add(htr);

                htr = new HtmlTableRow();
                //foreach (DataRow dr in dt.Rows)
                //{
                if (dt.Rows.Count > 0)
                {



                    for (int r = 0; r < dt.Rows.Count; r++)
                    {
                        int intRow = (r+1) % 2;
                        //int intRow = (dt.Rows.Count + 1) % 2;


                        htr = new HtmlTableRow();
                        htr.VAlign = "middle";
                        htr.Height = "25px";
                        htr.Attributes.Add("Class", "Grid_Row" + intRow.ToString());
                        htr.Attributes.Add("onMouseOver", "this.className='Grid_Scroll_BG'");
                        htr.Attributes.Add("onMouseOut", "this.className='" + "Grid_Row" + intRow.ToString() + "'");

                        htc = new HtmlTableCell();
                        htc.Width = "2px";
                        htr.Controls.Add(htc);

                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            htc = new HtmlTableCell();

                            SetRelatedRecordsAlignments(ref htc, dt.Columns[i].DataType.ToString());

                            string value = ApplyUserLocaleSettings(dt.Rows[r][i].ToString(),dt.Columns[i].DataType.ToString(),sUTC_Offset,cul);

                            Label lblobj = new Label();
                            //lblobj.Text = "&nbsp;"+dt.Rows[r][i].ToString()+"&nbsp;";
                            lblobj.Text = "&nbsp;"+value+"&nbsp;";
                            htc.Controls.Add(lblobj);
                            htr.Controls.Add(htc);
                        }
                        
                        ht.Controls.Add(htr);



                    }
                }
                else
                {
                    int intRow = 1;
                    htr = new HtmlTableRow();
                    htr.Attributes.Add("Class", "Grid_Row" + intRow.ToString());
                    htc = new HtmlTableCell();
                    Label lblobj = new Label();
                    lblobj.Text = "&nbsp;"+"No records available"+"&nbsp;";
                    htc.Controls.Add(lblobj);
                    htc.ColSpan = dt.Columns.Count+1;
                    htr.Controls.Add(htc);
                    ht.Controls.Add(htr);

                }

                // Add footer to the table 
                htc = new HtmlTableCell();
                Label lblempty = new Label();
                lblempty.Text = "";
                htc.Controls.Add(lblempty);
                htc.Attributes.Add("Class", "Grid_Header");
                htc.ColSpan = dt.Columns.Count+1;
                htr = new HtmlTableRow();
                htr.Height = "30px";
                htr.Controls.Add(htc);
                ht.Controls.Add(htr);

            //}
        }
        return ht;
    }

    private void SetRelatedRecordsAlignments(ref HtmlTableCell htc,string datatype)
    {
        try
        {
            switch (datatype.ToLower().Trim())
            {
                case "system.boolean":
                case "system.datetime":
                case "system.string":
                    htc.Align = "Left";
                    break;
                case "":
                case "system.decimal":
                case "system.int32":
                    htc.Align = "Right";
                    break;
                default:
                    htc.Align = "center";
                    break;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error : SetRelatedRecordsAlignments: "+ e.Message);
        }

    }

    private string ApplyUserLocaleSettings(string value,string datatype,string sutc_offset,CultureInfo cul)
    {
        string result = value;
        if (result.Trim() != "")
        {
            try
            {
                if (datatype.ToLower().Trim() == "system.datetime")
                {
                    Localization loc = new Localization();
                    result = loc.getDateTime4TimeZone(result, sutc_offset, false, false);
                }
                else if(datatype.ToLower().Trim() == "system.decimal")
                {
                    //result = Convert.ToDecimal(result,cul).ToS;
                    decimal dec = Convert.ToDecimal(result);
                    result = decimal.Parse(result, cul).ToString();
    
                }
            }
            catch
            {
            }
            finally
            {

            }
        }
        return result;
    }
    /// <summary>
    /// Added by srivatsan for creating Expanded notes section
    /// </summary>
    /// <param name="htc">refer the HtmlTableCell on which the expanded notes should be created</param>
    /// <param name="strkeyvalue">af_row_id of the parent record</param>
    /// <returns></returns>
    public HtmlTable CreateExpandedNotesSection(ref HtmlTableCell htcmain,string strkeyvalue)
    {
        HDDatabase HDD = new HDDatabase();
        HtmlTable ht = new HtmlTable();
        ht.Width = "100%";
        DataSet ds = new DataSet();
        HtmlTableRow htr = new HtmlTableRow();
        HtmlTableCell htc = new HtmlTableCell();
        try
        {
            if (strkeyvalue.Trim() != "")
            {
                DynamicDisplayI DDI = new DynamicDisplayI();
                string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
                DDI = null;

                string sql = "select * from sy_notes where related_af_row_id = '"+strkeyvalue+"' order by notes_date desc"; // Modified by 'Imran Gani' on 24-May-2012, to sort by notes date
                ds = HDD.GetDataset(sql);
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            //foreach(DataRow dr in ds.Tables[0].Rows)
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                htc = new HtmlTableCell();
                                htr = new HtmlTableRow();
                                CreateHtmlTableForNotes(ref htc, ds.Tables[0].Rows[i],sUTC_Offset);
                                htr.Controls.Add(htc);
                                ht.Controls.Add(htr);

                                if (i != ds.Tables[0].Rows.Count - 1)
                                {
                                    htc = new HtmlTableCell();
                                    htr = new HtmlTableRow();
                                    htc.Controls.Add(new LiteralControl("</br>"));
                                    htr.Controls.Add(htc);
                                    ht.Controls.Add(htr);
                                }

                            }

                            htcmain.Controls.Add(ht);

                        }
                        else
                        {
                            Label lbl = new Label();
                            lbl.Text = "No records available";
                            htcmain.Align = "center";
                            htcmain.Attributes.Add("class", "Grid_Row1");
                            htcmain.Controls.Add(lbl);
                        }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : CreateExpandedNotes : " + ex.Message);
        }
        finally
        {
            HDD = null;
            ds = null;
        }
        return ht;
        
    }

    private void CreateHtmlTableForNotes(ref HtmlTableCell htcmain, DataRow dr, string sUTC_Offset)
    {
        
        try
        {
            //if (dsPageInfo != null)
                //if(dsPageInfo.Tables.Count>0)
                    //if (dsPageInfo.Tables["Page Controls"] != null)
                   // {
                        //DataTable dtaPageCtrl = dsPageInfo.Tables["Page Controls"];
                        HtmlTable ht = new HtmlTable();
                        ht.CellPadding = 1;
                        ht.CellSpacing = 0;
                        ht.Width = "100%";
                        ht.Attributes.Add("class", "NotesTable");

                        #region HtmlTable type
                        //////ht.Style.Add("border-bottom", "20");
                        //////ht.Style.Add("border-bottom-color","Red");
                        //////ht.Style.Add("border-left", "20");
                        //////ht.Style.Add("border-left-color", "Red");
                        //////ht.Style.Add("border-right", "20");
                        //////ht.Style.Add("border-right-color", "Red");

                        //ht.Style.Add(HtmlTextWriterStyle.Margin, "10px");
                        //ht.Style.Add(HtmlTextWriterStyle.BorderWidth, "10px");

                        //ht.Style.Add("border","solid 1px #C0C0C0");
                        //ht.Style.Add("display", "block");
                        //style = "border:solid 1px #C0C0C0;display:block;"
                        //ht.BorderColor = "Red";
                        //ht.Border = 5; 
                        #endregion

                        HtmlTableRow htr = new HtmlTableRow();
                        HtmlTableCell htc = new HtmlTableCell();
                        if (htcmain != null)
                        {
                            //DataRow[] drr = dsPageInfo.Select("control_visible='true'", "control_seq");
                            if (dr !=null)
                            {
                                HDDatabase Hdd = new HDDatabase();
                                DataTable dt = Hdd.GetDataTable("select "+getUserDisplayName()+" as display_name,af_row_id from sy_usr");

                                ////// Header content
                                ////htc = new HtmlTableCell();
                                ////htc.Controls.Add(new LiteralControl("&nbsp;"));
                                ////htc.Attributes.Add("class", "Grid_Header");
                                ////htr.Controls.Add(htc);

                                htc = new HtmlTableCell();
                                htr = new HtmlTableRow();
                                htc.Attributes.Add("class", "Grid_Header");

                                /* Commanded by 'Imran gani' on 24-May-2012, to get the header with edit and copy button.
                                Label lblheader = new Label();
                                lblheader.Style.Add(HtmlTextWriterStyle.TextAlign, "Left");
                                lblheader.Text ="&nbsp;"+ manageDateTimeValues("DA", dr["notes_date"].ToString(),sUTC_Offset) + " - " + dr["title"].ToString();
                                
                                htc.Controls.Add(lblheader);
                                */
                                htc.Controls.Add(getHeaderInfoForViewAllNotes(dr, sUTC_Offset)); // Added by 'Imran gani' on 24-May-2012, to get the header with edit and copy button.
                                htr.Controls.Add(htc);
                                ht.Controls.Add(htr);
                                //

                                //// Content part
                                //htc = new HtmlTableCell();
                                //htc.Attributes.Add("class", "Grid_Row1");
                                //htc.Controls.Add(new LiteralControl("&nbsp;"));
                                //htr.Controls.Add(htc);

                                htc = new HtmlTableCell();
                                htc.Style.Add(HtmlTextWriterStyle.Left, "2px");
                                htc.Attributes.Add("class","Grid_Row1");
                                htc.Attributes.Add("style", "background-color:white");
                                htr = new HtmlTableRow();
                                Label lbldata = new Label();
                                lbldata.Text = CommonFunctions.SafeEncode(ReplaceSpecialCharacters(dr["notes"].ToString()));
                                htc.Controls.Add(lbldata);
                                htr.Controls.Add(htc);
                                ht.Controls.Add(htr);
                                //

                                // bottom row
                                htc = new HtmlTableCell();
                                htr = new HtmlTableRow();
                                HtmlTable htbottom = new HtmlTable();
                                htbottom.CellSpacing = 0;
                                htbottom.CellPadding = 0;
                                htbottom.Border = 0;
                                htbottom.Width = "100%";
                                HtmlTableRow htrbottom = new HtmlTableRow();
                                HtmlTableCell htcbottom = new HtmlTableCell();
                                htcbottom.Width = "33%";
                                htcbottom.Attributes.Add("class", "Dynamic_HtmlTableCell");
                                Literal lblowner = new Literal();
                                lblowner.Text = "<B>Owner: </B>"+GetOwnerID(dr["owner_id"].ToString(),dt);

                                htcbottom.Controls.Add(lblowner);
                                htrbottom.Controls.Add(htcbottom);

                                Literal lblmodifiedby = new Literal();
                                lblmodifiedby.Text = "<B>Last Modified By: </B>"+ GetOwnerID(dr["modified_by"].ToString(),dt);
                                htcbottom = new HtmlTableCell();
                                htcbottom.Width = "33%";
                                htcbottom.Attributes.Add("class", "Dynamic_HtmlTableCell");
                                htcbottom.Controls.Add(lblmodifiedby);
                                htrbottom.Controls.Add(htcbottom);

                                Literal lblmodified_at = new Literal();
                                lblmodified_at.Text = "<B>Last Updated at: </B>"+ manageDateTimeValues("DT",dr["modified_at"].ToString(),sUTC_Offset);
                                htcbottom = new HtmlTableCell();
                                htcbottom.Width = "33%";
                                htcbottom.Attributes.Add("class", "Dynamic_HtmlTableCell");
                                htcbottom.Controls.Add(lblmodified_at);
                                htrbottom.Controls.Add(htcbottom);

                                htbottom.Controls.Add(htrbottom);

                                //htrbottom.Controls.Add(htcbottom);
                                //htbottom.Controls.Add(htrbottom);

                                
                                htc.Controls.Add(htbottom);
                                htc.Attributes.Add("class","Grid_Row1");
                                htr.Controls.Add(htc);
                                ht.Controls.Add(htr);
                                //

                                #region olddesign
                                ////for (int i = 0; i < drr.Length; i++)
                                ////{
                                ////    if (drr[i]["control_attrib_id"].ToString().ToLower() == "title")
                                ////    {
                                ////        htr = new HtmlTableRow();
                                ////        htc = new HtmlTableCell();
                                ////        Label lbltitle = new Label();
                                ////        lbltitle.Text = dr[drr[i]["control_attrib_id"].ToString()].ToString();
                                ////        lbltitle.CssClass = "controlLabelFont";
                                ////        htc.ColSpan = 2;
                                ////        htc.Attributes.Add("class", "Grid_Header");
                                ////        htc.Controls.Add(lbltitle);
                                ////        htr.Controls.Add(htc);
                                ////        ht.Controls.Add(htr);

                                ////    }
                                ////    else
                                ////    {
                                ////        string data = dr[drr[i]["control_attrib_id"].ToString()].ToString();
                                ////        if (drr[i]["control_attrib_id"].ToString().ToLower() == "owner_id")
                                ////        {
                                ////            if (dt != null)
                                ////            {
                                ////                DataRow[] drrow = dt.Select("af_row_id='" + data.Trim() + "'");
                                ////                if (drrow.Length > 0)
                                ////                {
                                ////                    data = drrow[0]["user_id"].ToString();
                                ////                }
                                ////            }
                                ////        }
                                ////        if (drr[i]["control_attrib_type"].ToString().ToUpper() == "DA" || drr[i]["control_attrib_type"].ToString().ToUpper() == "DT")
                                ////        {
                                ////            data = manageDateTimeValues(drr[i]["control_attrib_type"].ToString(), data);
                                ////        }

                                        
                                ////        htr = new HtmlTableRow();
                                ////        htc = new HtmlTableCell();
                                ////        Label lblcaption = new Label();
                                ////        lblcaption.Text = "&nbsp;" + drr[i]["control_name"].ToString() + "&nbsp;";
                                ////        lblcaption.CssClass = "controlLabelFont";
                                ////        //htc.Attributes.Add("class", "pgForm_Title");
                                ////        htc.Controls.Add(lblcaption);
                                ////        htc.Width = "100px";
                                ////        htr.Controls.Add(htc);
                                ////        htc = new HtmlTableCell();
                                ////        //Label lbldata = new Label();
                                ////        LiteralControl lbldata = new LiteralControl();
                                ////        lbldata.Text = "&nbsp;" +  ReplaceSpecialCharacters(data) + "&nbsp;";
                                ////        //lbldata.CssClass = "controlFont";
                                ////        htc.Controls.Add(lbldata);
                                ////        htr.Controls.Add(htc);

                                ////        int iClass = i % 2;
                                ////        htr.Attributes.Add("Class", "Grid_Row" + iClass.ToString());

                                ////        ht.Controls.Add(htr);
                                ////    }
                                ////}
                                #endregion
                             
                                htcmain.Controls.Add(ht);
                            }
                        }
                    //}
            

        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CreateHtmlTableForNotes : "+ ex.Message);
        }
    }

    // Added by srivatsan for datetime conversion
    private string manageDateTimeValues(string type, string input, string sUTC_Offset)
    {
        if (type.Trim() == "")
            return input;
        if (input.Length < 1)
            return input;
        string ret = input;
        try
        {
            switch (type)
            {
                case "DA":
                    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                    //DateTime dt = DateTime.Parse(input);
                    //Localization ll = new Localization();
                    //ret = dt.ToString(ll.getDateFormat());
                    //ll = null;
                    #endregion
                    ret = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), DateTime.Parse(input));
                    break;
                case "DT":
                    Localization loc = new Localization();
                    ret = loc.getDateTime4TimeZone(input, sUTC_Offset, false, true);
                    loc = null;
                    //ret = input;
                    break;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageDateTimeValues. " + e.Message);
        }
        return ret;
    }

    // Added by srivatsan for replacing Special Charaters with Html tags
    private string ReplaceSpecialCharacters(string data)
    {
        try
        {
            if (data.Trim() != "")
            {
                data = data.Replace("\r\n", "<br/>");
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : ReplaceSpecialCharacters :"+ ex.Message);
        }
        return data;
    }

    //Added by srivatsan to get the owner id from af_row_id from datatable
    private string GetOwnerID(string af_row_id,DataTable dt)
    {
        string result = "";
        try
        {
            if (dt != null)
                if (dt.Rows.Count > 0)
                {
                    DataRow[] drr = dt.Select("af_row_id='" + af_row_id + "'");
                    if (drr.Length > 0)
                    {
                        //string userdiaplay = getUserDisplayName();

                        result = drr[0]["display_name"].ToString();
                    }
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetOwnerID :"+ex.Message);
        }
        return result;
    }

    public string getUserDisplayName()
    {
        HDDatabase HDD = new HDDatabase();
        string userDisplayField = HDD.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
        userDisplayField = userDisplayField.Trim().Length == 0 ? "user_id" : userDisplayField;
        return userDisplayField;
    }

    private HtmlTable getHeaderInfoForViewAllNotes(DataRow dr, string sUTC_Offset) // Implemented by 'Imran Gani' on 24-May-2012 
    {
        security HDS = new security();
        bool create = false; bool edit = false; bool delete = false;

        HtmlTable htHeader = new HtmlTable();
        try
        {
            htHeader.CellSpacing = 0;
            htHeader.CellPadding = 0;
            htHeader.Border = 0;
            htHeader.Width = "100%";
            HtmlTableRow htrHeader = new HtmlTableRow();
            HtmlTableCell htcHeader = new HtmlTableCell();

            htcHeader.Attributes.Add("class", "Grid_Header");

            Label lblheader = new Label();
            lblheader.Style.Add(HtmlTextWriterStyle.TextAlign, "Left");
            lblheader.Text = "&nbsp;" + manageDateTimeValues("DA", dr["notes_date"].ToString(), sUTC_Offset) + " - " + CommonFunctions.SafeEncode(dr["title"].ToString());

            htcHeader.Width = "80%";
            htcHeader.Controls.Add(lblheader);
            htrHeader.Controls.Add(htcHeader);

            htcHeader = new HtmlTableCell();
            htcHeader.Attributes.Add("class", "Grid_Header");

            string sTempUrl = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/') + 1);
            string sEditPage = "DynamicScreen.aspx";
            string strPagesetRowId = getPagesetId(dr["related_object_id"].ToString());
            string strMenuRowId = HttpContext.Current.Request.QueryString["mn"].ToString();
            string strText = "";
                                
            HDS.getPagesetRights(strPagesetRowId, ref create, ref edit, ref delete);
            
            if (create || edit)
            {
                strText = sTempUrl + sEditPage + "?pgs_id=" + strPagesetRowId + "&PK=" + dr["af_row_id"].ToString() + "&mn=" + strMenuRowId + "&MK=" + dr["related_af_row_id"].ToString();
                ImageButton E = new ImageButton();
                E = new ImageButton();
                E.ID = "btnEditTop";
                E.ImageUrl = "images/mb_button_edit.gif";
                E.ToolTip = "Edit";
                E.AlternateText = "Edit";
                E.PostBackUrl = strText;
                E.CausesValidation = false;
                //E.Click += new ImageClickEventHandler(btnEdit_Click);
                htcHeader.Controls.Add(E);
                htcHeader.Controls.Add(new LiteralControl("&nbsp;"));
            }

            if (create)
            {
                strText = sTempUrl + sEditPage + "?pgs_id=" + strPagesetRowId + "&PK=" + dr["af_row_id"].ToString() + "&mn=" + strMenuRowId + "&CPY=0&MK=" + dr["related_af_row_id"].ToString();
                ImageButton Copy = new ImageButton();
                Copy = new ImageButton();
                Copy.ID = "btnCpyTop";
                Copy.ToolTip = "Copy";
                Copy.AlternateText = "Copy";
                Copy.PostBackUrl = strText;
                Copy.CausesValidation = false;
                Copy.ImageUrl = "images/mb_button_copy.gif";
                //Copy.Click += new ImageClickEventHandler(btnCpy_Click);
                htcHeader.Controls.Add(Copy);
                htcHeader.Controls.Add(new LiteralControl("&nbsp;"));
            }
            /*
            if (delete)
            {
                ImageButton Del = new ImageButton();
                Del = new ImageButton();
                Del.ID = "btnDelTop";
                Del.ToolTip = "Delete";
                Del.AlternateText = "Delete";
                Del.CausesValidation = false;
                Del.ImageUrl = "images/mb_button_delete.gif";
                Del.OnClientClick = @"javascript:if(confirm(""Are you sure you want to delete '" + includeJavascriptEscapes(dr["title"].ToString()) + @"' ?"")){DeleteClick('" + dr["af_row_id"].ToString() + "','1');}else{return false;};";
                //Del.Click += new ImageClickEventHandler(btnDel_Click);
                htcHeader.Controls.Add(Del);
                htcHeader.Controls.Add(new LiteralControl("&nbsp;"));
            }
            */
            htcHeader.Align = "Right";
            htcHeader.Width = "20%";
            htrHeader.Controls.Add(htcHeader);
            htHeader.Controls.Add(htrHeader);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getHeaderButtonsForViewAllNotes:" + ex.Message);
        }
        return htHeader;
    }
    private string getPagesetId(string Object_Id) // Implemented by 'Imran Gani' on 24-May-2012 
    {
        HDDatabase HDD = new HDDatabase();
        string sPageset_Id = "";
        try
        {
            //string sSql = "select pageset_id from sy_pgs where af_row_id=(select pageset_id from sy_pgs_mem where page_id=(select page_id from sy_pg where object_id=(select object_id from sy_obj where af_row_id='" + Object_Id + "')));";
            string sSql = "select pageset_id from sy_pgs_mem where page_id=(select page_id from sy_pg where object_id=(select object_id from sy_obj where af_row_id='" + Object_Id + "'));";
            sPageset_Id = HDD.GetColumnValue(sSql);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getPagesetId : Error : " + ex.Message);
        }
        return sPageset_Id;
    }
    public string includeJavascriptEscapes(string inp) // Implemented by 'Imran Gani' on 24-May-2012 
    {
        if (inp.Trim() == "")
            return inp;
        try
        {
            string[] orgChars = new string[] { "\\", "\'", "\"" };
            string[] replaces = new string[] { "\\\\", "\\'", "\\\"" };
            for (int i = 0; i < orgChars.Length; i++)
                inp = inp.Replace(orgChars[i], replaces[i]);
            return inp;
        }
        catch (Exception e)
        {
            return inp;
        }
    }
}
